<template>
  <div class="course-section">
    <div class="section-header">
      <el-page-header @back="$router.go(-1)">
        <div slot="content" class="header-content">
          <div>{{ course.courseName }}</div>
        </div>
      </el-page-header>
      <div>
        <el-button type="primary" @click="handleShowAddSection"
          >添加阶段</el-button
        >
      </div>
    </div>
    <el-card>
      <el-tree
        :data="sections"
        :props="defaultProps"
        draggable
        :allow-drop="handleAllowDrop"
        v-loading="isLoading"
        @node-drop="handleSort"
      >
        <div class="inner" slot-scope="{ node, data }">
          <span>{{ node.label }}</span>
          <!-- section -->
          <span v-if="data.sectionName" class="actions">
            <el-button @click.stop="handleEditSectionShow(data)"
              >编辑</el-button
            >
            <el-button type="primary" @click.stop="handleShowAddLesson(data)"
              >添加课时</el-button
            >

            <el-button @click.stop="handleUpdateStatus(data, true)">{{
              getStatusName(data.status)
            }}</el-button>
          </span>
          <!-- lession -->
          <span v-else class="actions">
            <el-button @click="handleShowEditLesson(data, node.parent.data)"
              >编辑</el-button
            >
            <el-button type="success">上传视频</el-button>
            <el-button @click.stop="handleUpdateStatus(data, false)">{{
              getStatusName(data.status)
            }}</el-button>
          </span>
        </div>
      </el-tree>
    </el-card>
    <!-- /阶段列表 -->

    <!-- 添加阶段 -->
    <el-dialog title="章节信息" :visible.sync="isAddSectionShow">
      <section-form
        v-if="isAddSectionShow"
        :courseId="courseId"
        :courseName="course.courseName"
        @on-cancel="isAddLessonShow = false"
        @on-success="handleAddSection"
        :editSection="currentSection"
        :isEdit="isEditSection"
      />
    </el-dialog>
    <!-- /添加阶段 -->

    <!-- 添加课时 -->
    <el-dialog title="添加课时" :visible.sync="isAddLessonShow">
      <lession-form
        v-if="isAddLessonShow"
        :courseId="courseId"
        :courseName="course.courseName"
        :sectionId="lessionSection.id"
        :sectionName="lessionSection.sectionName"
        @on-cancel="isAddLessonShow = false"
        @on-success="handleAddLesson"
        :editLession="currentLession"
        :isEdit="isEditLession"
      />
    </el-dialog>
    <!-- /添加课时 -->

    <el-dialog title="提示" :visible.sync="isUpdateStatus" width="30%">
      <header class="toggle-header">
        <i class="el-icon-info"></i
        ><span>当前状态：{{ getStatusName(currentStatus) }}</span>
      </header>
      状态变更为：
      <el-select
        class="select-status"
        v-model="currentStatus"
        placeholder="请选择"
      >
        <el-option label="已隐藏" :value="0" />
        <el-option label="待更新" :value="1" />
        <el-option label="已更新" :value="2" />
      </el-select>

      <div class="dialog-footer">
        <el-button @click="isUpdateStatus = false">取 消</el-button>
        <el-button type="primary" @click="handleUpdatedStatus">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import {
  getSectionAndLesson,
  saveOrUpdateSection,
  getSectionById
} from '@/services/course-section'
import { getCourseById } from '@/services/course'
import { saveOrUpdateLesson } from '@/services/course-lesson'
import SectionForm from './components/section/form.vue'
import LessionForm from './components/lession/form.vue'

type TreeNode<T> = {
  data: T
  parent: {
    childNodes: TreeNode<T>[]
  }
};

export default Vue.extend({
  name: 'CourseSection',
  components: { SectionForm, LessionForm },
  props: {
    courseId: {
      type: [String, Number],
      required: true
    }
  },
  data () {
    const defaultProps = {
      children: 'lessonDTOS',
      label (data: { sectionName: string; theme: string }) {
        return data.sectionName || data.theme
      }
    }

    return {
      course: {},
      sections: [],
      defaultProps,
      isAddSectionShow: false,
      isAddLessonShow: false,
      currentSection: {},

      isEditSection: false,
      lessionSection: {},
      currentLession: {} as FromServer.LessionItem & { sectionName: string },

      isEditLession: false,
      isLoading: false,

      isUpdateStatus: false,
      currentStatus: -1,
      updateSectionStatus: false,
      currentStatusData: {} as any,
      statusChangeCount: 1
    }
  },

  created () {
    this.loadSections()
    this.loadCourse()
  },

  methods: {
    async loadCourse () {
      const { data } = await getCourseById(this.courseId)
      this.course = data.data
    },

    getStatusName (data: number) {
      return ({
        0: '已隐藏',
        1: '待更新',
        2: '已更新'
      } as { [key: number]: string })[data]
    },

    async loadSections () {
      const { data } = await getSectionAndLesson(this.courseId)
      this.sections = data.data
    },

    handleShowAddSection () {
      this.isEditSection = false
      this.isAddSectionShow = true
    },

    handleAddSection () {
      this.loadSections()
      this.isAddSectionShow = false
    },

    async handleEditSectionShow (section: FromServer.SectionItem) {
      if (section.id) {
        const { data } = await getSectionById(section.id)
        this.currentSection = data.data
        this.isEditSection = true
        this.isAddSectionShow = true
      }
    },

    async handleSectionStatusChange (section: FromServer.SectionItem) {
      await saveOrUpdateSection(section)
      this.$message.success('操作成功')
      this.isUpdateStatus = false
      this.loadSections()
      this.statusChangeCount++
    },

    async handleLessonStatusChange (lesson: FromServer.SectionItem) {
      await saveOrUpdateLesson(lesson)
      this.$message.success('操作成功')
      this.isUpdateStatus = false
      this.loadSections()
      this.statusChangeCount++
    },

    // 显示变更状态模态框
    handleUpdateStatus (
      data: FromServer.LessionItem | FromServer.SectionItem,
      isUpdateSection: boolean
    ) {
      this.currentStatus = data.status
      this.isUpdateStatus = true
      this.updateSectionStatus = isUpdateSection
      this.currentStatusData = data
    },

    // 执行装填变更
    handleUpdatedStatus () {
      this.currentStatusData.status = this.currentStatus
      if (this.updateSectionStatus) {
        this.handleSectionStatusChange(this.currentStatusData)
      } else {
        this.handleLessonStatusChange(this.currentStatusData)
      }
    },

    handleShowAddLesson (data: FromServer.SectionItem) {
      this.lessionSection = data
      this.isAddLessonShow = true
    },

    handleAddLesson () {
      this.loadSections()
      this.isAddLessonShow = false
    },

    handleShowEditLesson (
      lesson: FromServer.LessionItem,
      section: FromServer.SectionItem
    ) {
      this.lessionSection = section
      this.currentLession = lesson as any
      this.currentLession.sectionName = section.sectionName
      this.isEditLession = true
      this.isAddLessonShow = true
    },

    handleAllowDrop (
      draggingNode: TreeNode<FromServer.LessionItem>,
      dropNode: TreeNode<FromServer.LessionItem>,
      type: string
    ) {
      return (
        draggingNode.data.sectionId === dropNode.data.sectionId &&
        type !== 'inner'
      )
    },

    async handleSort (
      dragNode: TreeNode<FromServer.SectionItem>,
      dropNode: TreeNode<FromServer.LessionItem>
    ) {
      this.isLoading = true
      try {
        await Promise.all(
          dropNode.parent.childNodes.map((item, index: number) => {
            if (dragNode.data.lessonDTOS) {
              // 阶段
              return saveOrUpdateSection({
                id: item.data.id,
                orderNum: index + 1
              })
            } else {
              // 课时
              return saveOrUpdateLesson({
                id: item.data.id,
                orderNum: index + 1
              })
            }
          })
        )
        this.$message.success('排序成功')
      } catch (err) {
        console.log(err)
        this.$message.error('排序失败')
      }
      this.isLoading = false
    }
  }
})
</script>

<style lang="scss" scoped>
.section-header {
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-bottom: 30px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.toggle-header {
  margin-bottom: 20px;
  text-align: center;

  i {
    display: block;
    margin-bottom: 20px;
    font-size: 50px;
  }
}

.dialog-footer {
  text-align: right;
  margin-top: 30px;
}

.inner {
  flex: 1;
  padding: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #ebeef5;
}

::v-deep .el-tree-node__content {
  height: auto;
}

.select-status {
  width: calc(100% - 98px);
  margin-left: 8px;
}
</style>
